<template>
    <ul class="list">
      <li class="item" v-for="item of letters" @click="handleLetterClick" :key="item" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd" :ref="item">{{item}}</li>
    </ul>
</template>

<script>
  export default {
    name:'CityAlphabet',
    props:{
      cities:Object
    },
    computed:{
      letters (){
        const letters=[]
        for (let i in this.cities){
          letters.push(i)
        }
        return letters
      }
    },
    data (){
      return {
        touchStatus:false,
        startY:0,
        timer:null
      }
    },
    updated (){ //使用updated生命周期钩子   因为最开始渲染页面cities是一个空对象 所有有数据的时候会更新渲染一次页面 在这个时候把startY计算好  否则在touchmove中计算会消耗性能
      this.startY=this.$refs['A'][0].offsetTop  //获取A到顶部的距离
    },
    methods:{
      handleLetterClick (e){
        this.$emit('change',e.target.innerText)
      },
      handleTouchStart (){
        this.touchStatus = true
      },
      handleTouchMove (e){
        if(this.touchStatus){
          if(this.timer){
            clearTimeout(this.timer)
          }
          this.timer = setTimeout(()=>{
            const Y = e.touches[0].clientY-79   //获取鼠标点击到上边的距离  然后减去最头部
            const index = Math.floor((Y-this.startY)/20)  //A的高度为20  移动的距离减去A到顶部的距离/20取整就是每个字母到顶部的索引
            if(index >= 0 && index < this.letters.length){
              this.$emit('change',this.letters[index])   //把这个索引传到父组件  在有父组件传给List子组件形成兄弟组件传值
            }
          },16)
        }
      },
      handleTouchEnd (){
        this.touchStatus = false
      }

    }
  }
</script>

<style lang="stylus" scoped>
  @import "~styles/varibles.styl"
  .list
    position absolute
    top: 1.58rem
    display flex
    flex-direction column
    justify-content: center
    right: 0
    bottom: 0
    width: .4rem
    .item
      line-height: .4rem
      text-align: center
      color: $bgColor
</style>
